// @ts-nocheck

enum Degree {
  "重度" = "heavy",
  "中度" = "middle",
  "正常高值" = "normal",
  "偏低" = "little",
}

Page({
  data: {
    active: 0,
    title_to_top: 0,
    pressureList: [] as any[],
    patientUid: null as number | null, // 从微信 openId 获取到的用户id
  },

  onLoad() {
    const rect = wx.getMenuButtonBoundingClientRect();
    this.setData({ title_to_top: rect.height });

    this.getUserOpenId(); // ⬅️ 先获取 openId
  },

  // 🔹 第一步：获取微信 openId → 对应患者ID
  getUserOpenId() {
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: `http://127.0.0.1:4523/m1/7217678-6943978-default/patient/persureHeartRate/get_wx_open_id/${res.code}`,
            method: "GET",
            success: (resp) => {
              if (resp.data && resp.data.code === 0) {
                const id = resp.data.data.patientUid || resp.data.data.openId;
                this.setData({ patientUid: id });
                // 获取本周血压
                this.getWeeklyPressureData(id);
              } else {
                wx.showToast({ title: "openId获取失败", icon: "none" });
              }
            },
            fail: () => {
              wx.showToast({ title: "网络错误", icon: "none" });
            },
          });
        } else {
          wx.showToast({ title: "微信登录失败", icon: "none" });
        }
      },
    });
  },

  // 🔹 第二步：通过id获取本周血压数据
  getWeeklyPressureData(patientUid: number) {
    wx.request({
      url: "http://127.0.0.1:4523/m1/7217678-6943978-default/patient/persureHeartRate/weeklyPressureData",
      method: "GET",
      data: {
        patientUid: patientUid,
        weeksAgo: 0, // 0 = 本周
      },
      success: (res) => {
        if (res.data && res.data.code === 0 && Array.isArray(res.data.data)) {
          const list = res.data.data.map((item: any) => {
            const t = new Date(item.measureTime);
            return {
              dateYear: t.getFullYear(),
              dateMonth: String(t.getMonth() + 1).padStart(2, "0"),
              dateDay: String(t.getDate()).padStart(2, "0"),
              time: t.toTimeString().slice(0, 5),
              high_pressure: item.systolic,
              low_pressure: item.diastolic,
              degree: "",
            };
          });
          this.setData({ pressureList: list });
        } else {
          wx.showToast({ title: "血压数据获取失败", icon: "none" });
        }
      },
      fail: () => {
        wx.showToast({ title: "网络错误", icon: "none" });
      },
    });
  },

  onClickBack() {
    wx.navigateBack();
  },

  onClickRight() {
    wx.showToast({ title: "右侧按钮点击", icon: "none" });
  },

  onTabChange(event: any) {
    this.setData({ active: event.detail.index });
  },
});
